package cn.trigram.concurrent.limiter;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 定时限流器
 *
 * @version 1.0.0
 * @since 1.0.0
 */
public class TimeIntervalLimiter {

  /**
   * 记录上一次通过时间
   */
  private final AtomicLong lastTimeAtom = new AtomicLong(0);

  /**
   * 两次通过之间的时间窗口大小
   */
  private final long windowSizeMillis;

  public TimeIntervalLimiter(long interval, TimeUnit timeUnit) {

    this.windowSizeMillis = timeUnit.toMillis(interval);
  }

  public boolean tryAcquire() {

    long currentTime = System.currentTimeMillis();
    long lastTime    = lastTimeAtom.get();
    return currentTime - lastTime >= windowSizeMillis && lastTimeAtom
        .compareAndSet(lastTime, currentTime);
  }

}
